package job

import (
	"context"
	"log"
	"time"

	"intelli-dl-online-logo-go/model"
	"intelli-dl-online-logo-go/repository"
	"intelli-dl-online-logo-go/utils"

	"github.com/robfig/cron/v3"
)

type VipCheckJob struct {
	userRepo   repository.UserRepository
	vipLogRepo repository.UserVipLogRepository
}

func NewVipCheckJob(userRepo repository.UserRepository, vipLogRepo repository.UserVipLogRepository) *VipCheckJob {
	return &VipCheckJob{
		userRepo:   userRepo,
		vipLogRepo: vipLogRepo,
	}
}

func (j *VipCheckJob) Run() {
	ctx := context.Background()
	now := time.Now()

	// 获取所有VIP用户
	users, err := j.userRepo.FindByRole(ctx, 30)
	if err != nil {
		log.Printf(utils.ErrGetMongoUsers+": %v", err)
		return
	}

	for _, user := range users {
		// 获取用户最后一条VIP记录
		lastLog, err := j.vipLogRepo.FindLastByUserID(ctx, user.ID)
		if err != nil {
			log.Printf(utils.ErrGetMongoVipLog+": %s: %v", user.ID.Hex(), err)
			continue
		}

		// 检查是否过期
		if lastLog != nil && now.After(lastLog.EndTime.Time()) {
			// 更新用户角色为普通用户
			user1 := &model.User{
				ID:   user.ID,
				Role: 20,
			}
			_, err := j.userRepo.Update(ctx, user.ID, user1)
			if err != nil {
				log.Printf(utils.ErrUpdateMongoUser+": %s: %v", user.ID.Hex(), err)
			}
		}
	}
}

func StartVipCheckJob(userRepo repository.UserRepository, vipLogRepo repository.UserVipLogRepository) *cron.Cron {
	c := cron.New()
	job := NewVipCheckJob(userRepo, vipLogRepo)

	// 每天0点执行
	_, err := c.AddFunc("0 0 * * *", job.Run)
	if err != nil {
		log.Fatalf(utils.ErrAddVipCheckJob+": %v", err)
	}

	c.Start()
	return c
}
